package com.wantup.intecepter;

import com.wantup.controller.v6.User;
import com.wantup.controller.v6.UserChatController;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptorAdapter;

/**
 * @ClassName SocketChannelIntecpter
 * @Description 频道拦截器 类似管道 可以获取消息的 一些 meta数据
 * @Author zhaoluowei
 * @Date 2019/6/24  22:26
 * @Version 1.0
 */

public class SocketChannelIntecpter extends ChannelInterceptorAdapter {

    /**
     * 在消息被发送到 频道之前 调用
     *
     * @param message
     * @param channel
     * @return
     */
    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        System.out.println("SocketChannelIntecpter --> preSend");
        return super.preSend(message, channel);
    }

    /**
     * 发送消息后立马调用
     *
     * @param message
     * @param channel
     * @param sent    处理用户上下线
     */
    @Override
    public void postSend(Message<?> message, MessageChannel channel, boolean sent) {
        System.out.println("SocketChannelIntecpter --> postSend");
        //消息头访问器
        StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
        if (accessor.getCommand() == null) {
            return; //避免非stomp消息类型  例如心跳检测
        }

        String sessionId = accessor.getSessionAttributes().get("sessionId").toString();
        System.out.println("SocketChannelIntecpter : sessionId  ---> " + sessionId);

        switch (accessor.getCommand()) {
            case CONNECT:
                connectMethod(sessionId);
                break;

            case DISCONNECT:
                disConnectMethod(sessionId);
                break;

            case SUBSCRIBE:
                break;

            case UNSUBSCRIBE:
                break;

            default:
                break;
        }


    }

    //连接成功
    private synchronized void connectMethod(String sessionId) {
        System.out.println("connectMethod");


//        User user = new User("1", "");
//        UserChatController.onlineUser.put(sessionId,user);
    }

    //用户下线操作
    private synchronized void disConnectMethod(String sessionId) {
        System.out.println("disConnectMethod");
        UserChatController.onlineUser.remove(sessionId);
    }

    /**
     * 在完成发送之后进行调用，不管是否有异常发生一般用于资源清理
     *
     * @param message
     * @param channel
     * @param sent
     * @param ex
     */
    @Override
    public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, Exception ex) {
        super.afterSendCompletion(message, channel, sent, ex);
        System.out.println("SocketChannelIntecpter --> afterSendCompletion");
    }
}
